package chixing.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DeptTest {
    public static void main(String[] args) {
        //1.连接本地数据库（需要使用到其他jar包）
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        String url="jdbc:mysql://localhost:3306/empdb?useUnicode=true&characterEncoding=UTF-8";
        String username="root";
        String password="root";
        Connection connection = null;//数据库连接对象
        try {
            connection= DriverManager.getConnection(url,username,password);
            System.out.println("连接数据库成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //2.执行sql语句，添加数据到dept表
        String sql="insert into dept values(99,'企划部','上海')";
        PreparedStatement preparedStatement = null;//该类用于执行sql语句
        int rows=0;//表中受影响的行数
        //3.关闭连接
        try {
            preparedStatement = connection.prepareStatement(sql);
            rows=preparedStatement.executeUpdate();//执行sql语句的insert，update，delete和DDL操作
            if (rows>0)
                System.out.println("添加部门成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (preparedStatement!=null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
